<?php

class CIUser {

    public static function getInfo($id="")
    {
      return new CIUserAttibutes($id);
    }

    public static function getAuthInfo()
    {
      //Load instant
      $CI =& get_instance();
      $is_loggedin = $CI->session->userdata("is_loggedin");
      if(!$is_loggedin){
        return FALSE;
      }
      $user = new CIUserAttibutes();

      return $user->getAttrs();
    }

    public static function checkPermission($permission = "user"){
      $CI =& get_instance();
      $userdata = self::getAuthInfo();
      if(!$userdata){
        return false;
      }
      if($permission == "admin"){
        if($userdata["group"] != 2){
          return false;
        }
        return true;
      }
      if($permission == "user"){
        if($userdata["level"] > 0){
          return true;
        }
        return false;
      }
    }

}

class CIUserAttibutes {

    private $_user_id;
    private $_user_info;
    private $CI;

    public function __construct($user_id="")
    {
      //Load instant
      $this->CI =& get_instance();

      if($user_id==""){
        $is_loggedin = $this->CI->session->userdata("is_loggedin");
        if(!$is_loggedin){
          $this->_user_id = 0;
        }else{
          $userdata = $this->CI->session->userdata("user_data");
          $this->_user_id = $userdata['id'];
        }
      }else{
        $this->_user_id = $user_id;
      }

      if($this->_user_id != 0){
        //Load Model
        $this->CI->load->model("user_model");

        $this->_user_info = $this->CI->user_model->get($this->_user_id);
      }

    }

    public function getAttrs()
    {
        if (is_array($this->_user_info[0])) {
            return $this->_user_info[0];
        }
        return;
    }

    public function getAttr($attr)
    {
        if(empty($attr) OR empty($this->_user_info[0])){
          return;
        }
        if (array_key_exists($attr, $this->_user_info[0])) {
            return $this->_user_info[0][$attr];
        }
        return;
    }

}